package org.tissou.server.Services;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.tissou.client.Services.AuthentificationService;
import org.tissou.server.Utils.InterfaceMySQL;

import java.sql.SQLException;
import java.sql.ResultSet;

/**
 * Created by IntelliJ IDEA.
 * User: Manu
 * Date: Aug 2, 2009
 * Time: 10:25:20 AM
 * To change this template use File | Settings | File Templates.
 */
public class AuthentificationServiceImpl extends RemoteServiceServlet implements AuthentificationService {

    public AuthentificationServiceImpl() {
    }

    @Override
    public boolean authentifier(String utilisateur, String password) {
      InterfaceMySQL interfacePourLesRequetes = new InterfaceMySQL();
      try {
        utilisateur = utilisateur.toLowerCase();
        ResultSet result = interfacePourLesRequetes.RecupererDonnees(
            String.format("SELECT * FROM Passwords WHERE user='%s'", utilisateur));
        if (!result.next()) {

          // Le mec a jamais encore utilise son password, Sauvegarder celui la.
          interfacePourLesRequetes.EnvoyerQuery(
              String.format("INSERT INTO Passwords VALUES ('%s', PASSWORD('%s'))", utilisateur, password));
          return true;
        } else {
          result = interfacePourLesRequetes.RecupererDonnees(
            String.format("SELECT * FROM Passwords WHERE user='%s' AND pass=PASSWORD('%s')", utilisateur, password));
          if (result.next()) {
            return true;
          } else {
            return false;
          }
        }
      } catch (SQLException e) {
        return false;
      }
    }
}
